/*
 * @Author: Wangjun
 * @Date: 2021-07-21 10:04:44
 * @LastEditTime: 2021-08-12 11:34:01
 * @LastEditors: Wangjun
 * @Description:
 * @FilePath: \golib\outofdate\outofdate.go
 * hnxr
 */
//超期文件处理
package outofdate

import (
	"io/ioutil"
	"os"
	"strings"
	"time"

	"gitee.com/haodreams/golib/logs"
)

/**
 * @description: 删除过期的文件
 * @param {string} path 需要删除的根路径
 * @param {int} beforDays 需要删除多少天前的数据 0 不删除
 * @return {*}
 */
func DeleteOutofdateFile(path string, beforDays int) (err error) {
	if beforDays == 0 {
		return
	}
	if !(strings.HasSuffix(path, "/") || strings.HasSuffix(path, `\`)) {
		path += "/"
	}
	st := time.Now().Unix() - int64(86400*time.Duration(beforDays))
	timeout := time.Unix(st, 0).Format("20060102")
	fs, err := ioutil.ReadDir(path)
	if err != nil {
		return
	}
	for _, f := range fs {
		if f.Name() < timeout {
			if strings.HasPrefix(f.Name(), "20") {
				logs.Info("清理过期文件或目录", f.Name())
				os.RemoveAll(path + f.Name())
			}
		}
	}
	return
}
